package dome_006;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Description: [解决同样的问题的更高效的方法，使用AtomXXX类
 * AtomXXX类本身方法都是原子性的，但不能保证多个方法连续调用是原子性]</p>
 * Created on 2020/12/3
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Dome006_03 {
    //int count = 0;
    AtomicInteger count = new AtomicInteger(0);

    public /*synchronized*/ void test() {
        for (int i = 0; i < 10000; i++) {
            //count ++;
            count.incrementAndGet(); //count++
        }
    }

    public static void main(String[] args) {
        Dome006_03 dome006_03 = new Dome006_03();

        List<Thread> threads = new ArrayList<Thread>();

        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(dome006_03::test, "thread-" + i));
        }

        threads.forEach((o) -> o.start()); //JDK1.8新特性

        threads.forEach((o) -> { //JDK1.8新特性
            try {
                o.join(); //等线程执行完毕之后才执行主线程main
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        System.out.println(dome006_03.count);
    }

}
